package com.tiandang.controller;

import tiandang.core.utils.JsonUtils;
import com.tiandang.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tiandang.core.model.Song;
import tiandang.core.response.CommonReturnType;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("redis")
public class RedisController {
  @Autowired
  private StringRedisTemplate strRedis;

  @Autowired
  private RedisOperator redis;

  @GetMapping("/test")
  public Object test() {
    strRedis.opsForValue().set("hello", "fanjun");
    return CommonReturnType.success(strRedis.opsForValue().get("hello"));
  }

  @GetMapping("/test2")
  public Object test2() {

    Song song = new Song();
    song.setName("夜曲");
    song.setSinger("周杰伦");
    song.setCreatetime(new Date().getTime());
    song.setUpdatetime(new Date().getTime());

    strRedis.opsForValue().set("json:song", JsonUtils.objectToJson(song));
    Song jsonSong = JsonUtils.jsonToPojo(strRedis.opsForValue().get("json:song"), Song.class);

    return CommonReturnType.success(jsonSong);
  }

  @GetMapping("/test3")
  public Object test3() {

    Song song = new Song();
    song.setName("龙拳");
    song.setSinger("周杰伦");
    song.setCreatetime(new Date().getTime());
    song.setUpdatetime(new Date().getTime());

    Song song2 = new Song();
    song2.setName("醉赤壁");
    song2.setSinger("林俊杰");
    song2.setCreatetime(new Date().getTime());
    song2.setUpdatetime(new Date().getTime());

    Song song3 = new Song();
    song3.setName("美人鱼");
    song3.setSinger("林俊杰");
    song3.setCreatetime(new Date().getTime());
    song3.setUpdatetime(new Date().getTime());

    List<Song> songList = new ArrayList<>();
    songList.add(song);
    songList.add(song2);
    songList.add(song3);

    redis.set("json:info:songList", JsonUtils.objectToJson(songList), 2000);

    String songListJson = redis.get("json:info:songList");
    List<Song> songListBorn = JsonUtils.jsonToList(songListJson, Song.class);

    return CommonReturnType.success(songListBorn);
  }

}
